package com.retailshop.shopuser.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.retailshop.shopuser.common.*;
import com.retailshop.shopuser.entity.*;
import com.retailshop.shopuser.entity.hsys.HsysUserData;
import com.retailshop.shopuser.entity.hsys.HsysUserRoot;
import com.retailshop.shopuser.mapper.RedisUserNoMapper;
import com.retailshop.shopuser.mapper.UserMapper;
import com.retailshop.shopuser.mapper.UserNoMapper;
import com.retailshop.shopuser.mapper.UserRankMapper;
import com.retailshop.shopuser.service.UserNoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("userNoService")
public class UserNoServiceImpl implements UserNoService {

    @Autowired
    UserNoMapper userNoMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SMSConfig sconfig;

    @Autowired
    UserRankMapper userRankMapper;

    @Autowired
    FinaceConfig finace;

    @Autowired
    RedisUserNoMapper redisUserNoMapper;

    @Autowired
    RedisTemplate redisTemplate;


    int total = 0;

    private static final String KEY = "xlsphone2019";


    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userNoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(UserNo record) {
        return userNoMapper.insert(record);
    }

    @Override
    public int insertSelective(UserNo record) {
        return userNoMapper.insertSelective(record);
    }


    @Override
    public UserNo selectByPrimaryKey(Integer id) {
        return userNoMapper.selectByPrimaryKey(id);
    }


    @Override
    public int updateByPrimaryKeySelective(UserNo record) {
        return userNoMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int findLoginPwd(UserNo record) {
        return userNoMapper.findLoginPwd(record);
    }


    @Override
    public int updateByPrimaryKey(UserNo record) {
        return userNoMapper.updateByPrimaryKey(record);
    }


    @Override
    public List<UserNo> selectUserNoByUserId(int userId) {
        return userNoMapper.selectUserNoByUserId(userId);
    }


    /**
     * 注册
     *
     * @param map
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public UserNo userRegister(Map<String, Object> map, HttpServletRequest request) throws Exception {
        String name = null;
        String phone = null;
        String code = null;
        String SMSCode = null;
        UserNo userNo = null;
        String cardId = null;
        String nick = null;
        String salt = null;
        String payPwd = null;
        String pwd = null;

        int shareId = 62240;
        int rankid = 1;
        int row1 = 0;
        int row = 0;
        int userId = 0;

        if (map != null && map.get("phone") != null && map.get("code") != null) {
            if (map.get("shareId") != null && map.get("shareId") != "") {
                shareId = Integer.parseInt((String) map.get("shareId"));
            }

            phone = (String) map.get("phone");
            code = (String) map.get("code");
            String codeTime = (String) map.get("codeTime");
            String requestHash = (String) map.get("hash");
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MINUTE, 0);
            String currentTime = sf.format(c.getTime());
            String hash = MD5Util.getMD5Code(KEY + "@" + codeTime + "@" + code);
            if (OtherConstants.RegexpPhone(phone)) {
                if (codeTime.compareTo(currentTime) > 0) {//注册
                    if (requestHash.equalsIgnoreCase(hash)) {
                        User user = new User();
                        user.setPhone(phone);
                        if (name == null) {
                            name = "xls" + phone;
                        }
                        if (cardId == null) {
                            cardId = "5********";
                        }
                        user.setName(name);
                        user.setState(true);
                        user.setSort((short) 100);
                        user.setCardid(cardId);
                        row1 = userMapper.insertSelective(user);
                        userId = user.getId();

                        if (row1 > 0) {
                            userNo = new UserNo();
                            userNo.setNo("xls" + phone);
                            userNo.setRankId(rankid);
                            userNo.setRegisterTime(new Date());
                            userNo.setSort((short) 100);

                            if (nick == null) {
                                nick = "xls" + phone;
                            }
                            userNo.setNick(nick);
                            if (salt == null) {
                                salt = "";
                            }
                            userNo.setSalt(salt);

                            userNo.setShare(shareId);//推荐人

                            userNo.setUserId(userId);
                            if (payPwd == null) {
                                payPwd = "";
                            }
                            if (pwd == null) {
                                pwd = "000000";
                            }
                            userNo.setPaypwd(payPwd);
                            userNo.setPwd(MD5Util.getEncryptedPwd(pwd));
                            row = userNoMapper.insertSelective(userNo);
                        }
                        if (row1 > 0 && row > 0) {
                            //注册成功，返代金券
                            RestTemplate restTemplate = new RestTemplate();
                            String url = HttpRequestConfig.finaceServerUrl + "/wap/Add";
                            HttpHeaders headers = new HttpHeaders();
                            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                            MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
                            paramMap.add("userNoId", userNo.getId() + "");
                            paramMap.add("classify", "3");
                            paramMap.add("amount", finace.getVouchers() + "");
                            paramMap.add("remark", userNo.getNo() + "注册赠送");

                            HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(paramMap, headers);
                            ResponseEntity<String> resp = restTemplate.postForEntity(url, req, String.class);

                            //注册成功，返代给推荐人金券
                            MultiValueMap<String, String> paramMap1 = new LinkedMultiValueMap<>();
                            paramMap1.add("userNoId", shareId + "");
                            paramMap1.add("classify", "3");
                            paramMap1.add("amount", finace.getVouchers() + "");
                            paramMap1.add("remark", userNo.getNo() + "注册赠送");

                            HttpEntity<MultiValueMap<String, String>> req1 = new HttpEntity<>(paramMap1, headers);
                            ResponseEntity<String> resp1 = restTemplate.postForEntity(url, req1, String.class);
                            return userNo;
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                } else {//p
                    return null;
                }


            } else {
                return null;
            }

        } else {
            return null;
        }

    }

    /**
     * 账号登录
     *
     * @param map
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public UserNo userLoginByPwd(Map<String, Object> map, HttpServletRequest request) throws Exception {
        if (map != null) {
            String userNo = (String) map.get("userNo");//账号
            String pwd = (String) map.get("password");

            if (userNo != null && userNo != "") {
                UserNo userNo1 = userNoMapper.selectUserNoByUserNo(userNo);//根据用户编号查询用户
                if (userNo1 != null) {
                    String pwdIndb = userNo1.getPwd();
                    if (null != pwdIndb) {
                        boolean flag = false;
                        flag = MD5Util.validPassword(pwd, pwdIndb);
//                        boolean flag = true;
                        if (flag) {//登录成功
                            request.getSession().setAttribute("userNo", userNo1);

                            return userNo1;

                        } else {
                            return null;
                        }
                    } else {//荟生账号登录
                        String par = "userid=" + userNo;
                        par += "&password=" + pwd;
                        par += "&clientIp=127.0.0.1";
                        par += "&encryptStr=60f5a3c2ab917609282ebaafc6365589";
                        String url = "http://yc.huisheng2688.com/hsycMgr/app/getUserInfo.do";
                        String json = HttpRequest.sendPost(url, par);
                        System.out.println(json);
                        HsysUserRoot hsysUserRoot = JSON.parseObject(json, HsysUserRoot.class);
                        if (hsysUserRoot.isSuccess()) {

                            //读取User信息
                            User user = userMapper.selectByPrimaryKey(userNo1.getUserId());

                            if (user != null) {

                                HsysUserData hsysUserData = hsysUserRoot.data.get(0);

                                //更新数据,电话号码

                                boolean bit = false;
                                boolean bitn = false;

                                //判断是否改名
                                if (user.getName() != hsysUserData.getUsername()) {
                                    user.setName(hsysUserData.getUsername());
                                    userNo1.setNick(hsysUserData.getUsername());//更新用户编号的昵称
                                    bitn = true;
                                    bit = true;
                                }

                                //判断是否改身份证
                                if (user.getCardid() != hsysUserData.getIdcard()) {
                                    user.setCardid(hsysUserData.getIdcard());
                                    bit = true;
                                }

                                //判断是否改手机号码
                                if (user.getPhone() != hsysUserData.getCellphone()) {
                                    //修改的手机号是否存在
                                    User user1 = userMapper.queryUserByPhone(hsysUserData.getCellphone());
                                    if (user1 != null) {
                                        userNo1.setUserId(user1.getId());
                                        bitn = true;
                                    } else {
                                        user.setPhone(hsysUserData.getCellphone());
                                        bit = true;
                                    }

                                }

                                if (bit) {
                                    userMapper.updateByPrimaryKeySelective(user);
                                }

                                if (bitn) {
                                    userNoMapper.updateByPrimaryKeySelective(userNo1);
                                }

                                return userNo1;
                            } else {
                                return null;
                            }

                        } else {
                            return null;
                        }

                    }
                } else {
                    return null;
                }

            } else {
                return null;
            }


        }

        return null;
    }

    /**
     * 用户手机号登录
     *
     * @param map
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public UserNo userLoginByPhone(Map<String, Object> map, HttpServletRequest request) throws Exception {
        if (map.get("code") != null && "" != map.get("code")) {
            String phone = (String) map.get("phone");
            String code = (String) map.get("code");
            String codeTime = (String) map.get("codeTime");
            String requestHash = (String) map.get("hash");
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MINUTE, 0);
            String currentTime = sf.format(c.getTime());
            User us = null;
            int usId = 0;
            UserNo userNo = null;
            if (codeTime.compareTo(currentTime) > 0) {
                String hash = MD5Util.getMD5Code(KEY + "@" + codeTime + "@" + code);
                if (requestHash.equalsIgnoreCase(hash)) {
                    //查询用户手机号，默认一个账号登录
                    User user = new User();
                    user.setPhone(phone);
                    //读取缓存数据
                    Object obj = redisTemplate.opsForValue().get("user" + phone);
                    if (obj != null) {
                        User user1 = (User) obj;
                        if (user1 != null) {
                            usId = user1.getId();
                        }
                    } else {
                        List<User> userList = userMapper.selectUserByPhone(user);
                        if (userList != null && userList.size() != 0) {
                            for (int i = 0; i < userList.size(); i++) {
                                us = userList.get(0);
                                break;
                            }
                            usId = us.getId();
                        }
                    }

                    List<UserNo> userNoList = null;
                    //从缓存中获取数据
                    Object object = redisTemplate.opsForValue().get("userId" + usId);
                    if (object != null) {
                        userNoList = (List<UserNo>) object;
                    }else{

                        //根据用户ID查询编号
                        userNoList = userNoMapper.selectUserNoByUserId(usId);
                    }


                    if (!userNoList.isEmpty()) {
                        userNo = userNoList.get(0);
                        return userNo;
                    } else {
                        return null;
                    }

                } else {
                    return null;
                }
            } else {
                return null;
            }
        }

        return null;
    }


    /**
     * 用户设置密码
     *
     * @param
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public boolean updateUserNoLoginPwd(HttpServletRequest request) throws Exception {
        String phone = "";
        String code = "";
        String codeTime = "";
        String requestHash = "";
        int userNoId = 0;
        String pwd = "";
        UserNo userNo1 = null;
        phone = request.getParameter("phone");
        code = request.getParameter("code");

        codeTime = request.getParameter("codeTime");
        requestHash = request.getParameter("hash");
        userNoId = Integer.parseInt(request.getParameter("userNoId"));
        pwd = request.getParameter("pwd");

        String encrytPwd = null;
        boolean flag = CheckCode.checkCode(phone, code, codeTime, requestHash);


        if (flag) {//验证
            encrytPwd = MD5Util.getEncryptedPwd(pwd);
            UserNo userNo = new UserNo();
            userNo.setPwd(encrytPwd);
            userNo.setId(userNoId);
            int row = userNoMapper.updateByPrimaryKeySelective(userNo);
            if (row > 0) {//更新缓存
                Object object = redisTemplate.opsForValue().get("userNo" + userNo.getId());
                if (object != null) {
                    userNo1 = (UserNo) object;
                    if (userNo1 != null) {
                        userNo1.setPwd(encrytPwd);
                        redisTemplate.opsForValue().set("userNo" + userNo.getId(), userNo1);
                    }
                }

                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }


    }

    /**
     * 发送验证码
     * @param phone
     * @param request
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendCodeByPhone(String phone, HttpServletRequest request) throws Exception {
        String sendResult = null;
        String json = "{\"stat\":\"666004\",\"message\":\"发送验证码错误\"}";
        Map<String, Object> map = new HashMap<>();
        //发送验证码
        String randomNumCode = Md5.getRandomNumCode(4);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 10);
        String currentTime = sf.format(c.getTime());// 生成10分钟后时间，用户校验是否过期

//        sendResult = SMSAPI.SMSAPI_Reg_code(phone, randomNumCode, sconfig);
//        sendResult = SMSAPI.SMSAPI_Reg_code(phone, randomNumCode, sconfig);
        SendSmsResponse response = SmsDemo.sendSms(phone, randomNumCode);
        if ("OK".equalsIgnoreCase(response.getCode()) && "OK".equalsIgnoreCase(response.getMessage())) {
            json = "{\"stat\":\"100\",\"message\":\"发送成功！\"}";
        }
        String hash = MD5Util.getMD5Code(KEY + "@" + currentTime + "@" + randomNumCode);
        map.put("hash", hash);
        map.put("sendResult", json);
        map.put("codeTime", currentTime);
        return map;
    }

    /**
     * 申请店铺
     *
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public boolean applyStore(HttpServletRequest request) throws Exception {
        int userNoId = 0;
        String license = "";
        String certificate = "";
        String userNoIds = request.getParameter("userNoId");
        String storeName = request.getParameter("storeName");

        String storeLogo = "http://resources.ycsqd.com/201904160809426943.jpg";

        license = request.getParameter("license");
        certificate = request.getParameter("certificate");

        if (StringUtil.isNumeric(userNoIds)) {
            userNoId = Integer.parseInt(userNoIds);
        }

        UserNo userNo = new UserNo();
        userNo.setId(userNoId);
        userNo.setLicense(license);
        userNo.setCertificate(certificate);
        userNo.setHeadPic("http://resources.ycsqd.com/201904160809426943.jpg");
        int row = userNoMapper.updateByPrimaryKeySelective(userNo);
        UserNo userNo1 = null;
        if (row > 0) {
            //增加店铺
            String url = HttpRequestConfig.orderServerUrl + "/wap/applyStoreInfo";

            String storeUserId = "userNoId=" + userNoId + "&storeName=" + storeName + "&storeLogo=" + storeLogo;
            String result = HttpRequest.sendGet(url, storeUserId);
            JSONObject jsonobject = JSONObject.parseObject(result);
            String code = jsonobject.get("code").toString();
            if ("000000".equalsIgnoreCase(code)) {
                //更新用户信息
                Object object = redisTemplate.opsForValue().get("userNo" + userNo.getId());
                if (object != null) {
                    userNo1 = (UserNo) object;
                    if (userNo1 != null) {
                        userNo1.setLicense(license);
                        userNo1.setCertificate(certificate);
                        userNo1.setHeadPic("http://resources.ycsqd.com/201904160809426943.jpg");
                        redisTemplate.opsForValue().set("userNo" + userNo.getId(), userNo1);
                    }
                }

                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }


    /**
     * 修改支付密码
     *
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public boolean updatePayPwd(HttpServletRequest request) throws Exception {

        String phone = "";
        String code = "";
        String codeTime = "";
        String requestHash = "";
        int userNoId = 0;
        String payPwd = "";

        phone = request.getParameter("phone");
        code = request.getParameter("code");

        codeTime = request.getParameter("codeTime");
        requestHash = request.getParameter("hash");
        userNoId = Integer.parseInt(request.getParameter("userNoId"));
        payPwd = request.getParameter("payPwd");
        UserNo userNo1 = null;
        boolean flag = CheckCode.checkCode(phone, code, codeTime, requestHash);
        if (flag) {//修改密码
            UserNo userNo = new UserNo();
            userNo.setId(userNoId);
            userNo.setPaypwd(MD5Util.getEncryptedPwd(payPwd));
            int row = userNoMapper.updateByPrimaryKeySelective(userNo);
            if (row > 0) {
                //更新缓存
                Object object = redisTemplate.opsForValue().get("userNo" + userNo.getId());
                if (object != null) {
                    userNo1 = (UserNo) object;
                    if (userNo1 != null) {
                        userNo1.setPwd(MD5Util.getEncryptedPwd(payPwd));
                        redisTemplate.opsForValue().set("userNo" + userNo.getId(), userNo1);
                    }
                }
                return true;

            } else {
                throw new RuntimeException();

            }

        } else {
            return false;
        }


    }


    /**
     * 获取个人资料
     *
     * @param userNoId
     * @return
     */
    @Override
    public UserInfo getUserInfo(int userNoId) {

        return userNoMapper.getUserInfo(userNoId);
    }

    /**
     * 获取分享人信息
     *
     * @param userNoId
     * @return
     */
    @Override
    public List<UserSharerInfo> getUserSharesInfo(int userNoId) {
        return userNoMapper.getUserSharesInfo(userNoId);
    }

    @Override
    public SimpleUserInfo getSimpleUserInfo(int userNoId) {
        return userNoMapper.getSimpleUserInfo(userNoId);
    }

    @Override
    public List<UserNo> getReCommender(int userNoId) {
        return userNoMapper.getReCommender(userNoId);
    }


    @Override
    public List<UserNo> selectList() {
        return userNoMapper.selectList();
    }


    @Transactional
    @Override
    public int updatSharerTotal(UserNo userNo) {
        return userNoMapper.updatSharerTotal(userNo);
    }


    @Override
    public List<UserNoLoginInfo> getUserNoList(int userNoId) {
        return userNoMapper.getUserNoList(userNoId);
    }


    @Override
    public UserAndUserNoInfo selectUserAndUserNoByNo(String userNo) {
        return userNoMapper.selectUserAndUserNoByNo(userNo);
    }


//    public List<UserNo> getShare(int userNoId){
//
//        List<UserNo> userNoList=  userNoMapper.getReCommender(userNoId);
//        if(userNoList==null){
//            return null;
//        }
//
//        return userNoList;
//    }
//
//
//    public void getcount(List<Integer> list){
//
//        List<Integer> list1=new ArrayList<>();//里面
//        List<Integer> list2=new ArrayList<>();//外面
//
//        List<UserNo> userNoList1=null;
//
//        if(list.size()==0){return ;}
//        for (int i = 0; i <list.size() ; i++) {
//
//            System.out.println("----->"+list.size()+"id=="+list.get(i));
//
//            total++;
//            userNoList1 =getShare(list.get(i));
//            if(userNoList1==null||userNoList1.size()==0){continue;}
//
//
//            for (int k = 0; k <userNoList1.size() ; k++) {
//
//                int Id=userNoList1.get(k).getId();
//                list1.add(Id);
//                System.out.println("第一层："+Id);
//            }
//
//
//
//        }
//
//        //第二层：数据
//        for (int m = 0; m <list1.size() ; m++) {
//            int s=list1.get(m);
//            list2.add(s);
//
//        }
//        System.out.println("list2:"+list2.size());
//
//        getcount(list2);
//
//
//    }

    @Override
    public UserNo getOwner(int userNoId) {
        UserNo userNo = userNoMapper.selectUser(userNoId);
        if (userNo != null) {
            if (userNo.getRankId() == 3 || userNo.getRankId() == 4 || userNo.getRankId() == 5 || userNo.getRankId() == 6) {
                return userNo;
            } else {
                return getOwner(userNo.getShare());
            }
        }
        return null;
    }

    @Override
    public UserNo getVera(int userNoId) {
        UserNo userNo = userNoMapper.selectUser(userNoId);
        if (userNo != null) {
            if (userNo.getVera()) {
                return userNo;
            } else {
                return getVera(userNo.getShare());
            }
        }
        return null;
    }

    @Override
    public UserNo checkPayPwd(Map<String, Object> map, HttpServletRequest request) throws Exception {
        if (map != null) {
            String userNoId = (String) map.get("userNoId");//账号id
            int intUserNoId = 0;
            try {
                intUserNoId = Integer.parseInt(userNoId);
            } catch (Exception e) {
            }
            String payPwd = (String) map.get("payPwd");
            if (intUserNoId > 0) {
                UserNo userNo1 = userNoMapper.selectByPrimaryKey(intUserNoId);//根据用户编号查询用户
                if (userNo1 != null) {
                    String pwdIndb = userNo1.getPaypwd();
                    if (null != pwdIndb) {
                        boolean flag = false;
                        flag = MD5Util.validPassword(payPwd, pwdIndb);
                        if (flag) {//密码验证通过
                            return userNo1;
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        return null;
    }

    @Override
    public List<UserNo> selectUserNoByList(Map<String, Object> map, HttpServletRequest request) throws Exception {
        List<UserNo> list = new ArrayList<>();
        if (map != null) {
            String userNoListStr = (String) map.get("userNoIds");
            String ss = "[" + userNoListStr + "]";
            List<String> noListno = JSON.parseArray(ss, String.class);
            list = userNoMapper.selectUserNoByList(noListno);
        }
        return list;
    }

    @Override
    public List<UserNo> getSupplier() {
        return userNoMapper.getSupplier();
    }

    @Override
    public int updateRankId(int rankId, int userNoId) {
        return userNoMapper.updateRankId(rankId,userNoId);
    }

    @Override
    public List<SwitchUserNo> getUserNoListByUserId(int userId, int userNoId) {
        return userNoMapper.getUserNoListByUserId(userId, userNoId);
    }

    @Override
    public UserNo getUserNoByUserNo(String userNo) {
        return userNoMapper.getUserNoByUserNo(userNo);
    }


}